package login_controller

import (
	"jwt-demo/dao"
	database_redis "jwt-demo/database/redis"
	jwt_util "jwt-demo/util"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
	var user dao.User
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(200, gin.H{
			"code":    400,
			"message": "参数错误",
		})
		return
	}
	if user.Username == "" || user.Password == "" {
		c.JSON(200, gin.H{
			"code":    400,
			"message": "参数错误",
		})
		return
	}
	token, err := jwt_util.GenerateToken(user.Username)

	if err != nil {
		c.JSON(200, gin.H{
			"code":    400,
			"message": "生成token失败",
		})
		return
	}

	if !database_redis.SetKey(user.Username, token, 60*60) {
		c.JSON(200, gin.H{
			"code":    400,
			"message": "redis设置失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code":    200,
		"message": "登录成功",
		"data": gin.H{
			"token": token,
		},
	})
}
